// pages/user/erji//myOrder/myOrder.js
var base = require('../../../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数

const { timePeisZh, timestampToYMD } = require('../../../../utils/util.js')
const { getUserToken, getUserInfo } = require('../../../../lib/user.js')
const { URL } = require('../../../../lib/urls.js')
const { HTTP } = require('../../../../lib/http.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: [],
    nameArry: [_('全部'), _('待付款'), _('待发货'), _('配送中'), _('已完成'), _('已取消')],
    isFromSearch: true, // 用于判断searchSongList数组是不是空数组，默认true，空的数组
    searchPageNum: 1,   // 设置加载的第几次，默认是第一次
    callbackcount: 6,   //返回数据的个数
    searchLoading: false, //"上拉加载"的变量，默认false，隐藏
    searchLoadingComplete: false,  //“没有数据”的变量，默认false，隐藏
    isShowNullView: false,
    nowIndex: 0,//当前选中code
    dataList:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      _t: base._t(), //翻译
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.fetchDataList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  //标签点击事件
  onSelectEvent: function (e) {
    const index = e.detail.currentTarget.dataset.index;
    if (this.data.nowIndex == index) {
      return;
    }
    this.setData({
      nowIndex: index,
      isFromSearch: true,
      searchPageNum: 1,
      searchLoading: false,
      searchLoadingComplete: false,
    })
    this.fetchDataList();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;
    that.setData({
      searchPageNum: 1,  //每次触发上拉事件，把searchPageNum+1
      isFromSearch: true  //触发到上拉事件，把isFromSearch设为为false
    });
    that.fetchDataList();
  },
  //滚动到底部触发事件
  onReachBottom: function () {
    let that = this;
    if (that.data.searchLoading && !that.data.searchLoadingComplete) {
      that.setData({
        searchPageNum: that.data.searchPageNum + 1,  //每次触发上拉事件，把searchPageNum+1
        isFromSearch: false  //触发到上拉事件，把isFromSearch设为为false
      });
      that.fetchDataList();
    }
  },
  getOrderStatusStr: function (status,type){
    //type 1 外卖 2堂食 3自取
    // 外卖状态 ： 1 未支付 2 待接单 3 配送中 4 订单完成 5 订单取消 7 待派送
    // 堂吃 ： 1 未支付 2 待确认  3 已到店 4 订单完成 5 订单取消 7 已确认
    // 自取：  1 未支付 2 待确认 3 准备完成 / 待取件 4 已完成 5 订单取消 7 已确认 / 准备中 
    var statusStr="待付款";
    switch (status) {
      case 2:
        statusStr = type == 1 ? "待接单" :"待确认"
        break;
      case 3:
        if(type==1)
          statusStr = "配送中"
        else if(type==2)
          statusStr = "已到店"
        else
          statusStr = "待取件"
        break;
      case 4:
        statusStr = "订单完成"
        break;
      case 5:
        statusStr = "订单取消"
        break;
      case 7:
        if (type == 1)
          statusStr = "待派送"
        else if (type == 2)
          statusStr = "已确认"
        else
          statusStr = "准备中"
        break;
      default:
        statusStr = "待付款"
    } 
    return statusStr;
  },
  fetchDataList: function () {
    wx.showLoading({
      title: '加载中...'
    })
    let that = this;
    let searchPageNum = that.data.searchPageNum,//把第几次加载次数作为参数
      callbackcount = that.data.callbackcount; //返回数据的个数
    HTTP({
      url: URL.order.getOrderList,
      userToken: getUserToken(),
      data: {
        Status: that.data.nowIndex,
        PageIndex: searchPageNum,
        PageSize: callbackcount,
      },
      success: (ress) => {
        wx.stopPullDownRefresh();
        wx.hideLoading();
        var res = ress.Data;
        if (res.OrderInfoInfos.length > 0) {
          console.log("hlw:" + res)
          let searchList = [];
          var list = [];
          for (var i = 0; i < res.OrderInfoInfos.length; i++) {
            var model = res.OrderInfoInfos[i];
            if (model) {
              if (model.DeliveryWay==1){
                model.typeStr = _("外卖");
              } else if (model.DeliveryWay==2){
                model.typeStr = _("堂食");
              }else{
                model.typeStr = _("自取");
              }
              model.statusStr = that.getOrderStatusStr(model.OrderStatus, model.DeliveryWay);
              list.push(model);
            }
          }
          //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加
          this.data.isFromSearch ? searchList = list : searchList = that.data.dataList.concat(list)
          this.setData({
            dataList: searchList, //获取数据数组
            searchLoading: true,   //把"上拉加载"的变量设为false，显示
            isShowNullView: searchList.length > 0 ? false : true
          });
          if (res.OrderInfoInfos.length < callbackcount) {
            //数据已加载完毕
            that.setData({
              searchLoadingComplete: true, //把“没有数据”设为true，显示
              searchLoading: false  //把"上拉加载"的变量设为false，隐藏
            });
          }
          //没有数据了，把“没有数据”显示，把“上拉加载”隐藏
        } else {
          if (that.data.searchPageNum == 1) {
            that.setData({
              dataList: [],
              isShowNullView: true
            })
          }
          that.setData({
            searchLoadingComplete: true, //把“没有数据”设为true，显示
            searchLoading: false  //把"上拉加载"的变量设为false，隐藏
          });
        }
      }, fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  payOrder: function(e) {
    wx.showLoading({
      title: '订单支付中...'
    })
    const index = e.currentTarget.dataset.index;
    var ordermodel=this.data.dataList[index];
    var that = this;
    HTTP({
      url: URL.order.payOrder,
      userToken: getUserToken(),
      data: {
        OrderInfoCode: ordermodel.OrderInfoCode,
        MemberId: getUserInfo().memberId,
      },
      success: (ress) => {
        var res = ress.Data;
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign,
          success: function (res) {
            //支付成功
            wx.showToast({
              title: _('支付成功'),
              icon: 'succes',
              duration: 1000,
              mask: true
            })
            that.fetchDataList();//刷新订单列表
          },
          fail: function (res) {
            console.log("hlwfail:" + res.data)
            wx.showToast({
              title: _('支付失败'),
              icon: 'none'
            })
          }
        })
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  cancelorder: function (e) {
    wx.showLoading({
      title: '订单取消中...'
    })
    const index = e.currentTarget.dataset.index;
    var ordermodel = this.data.dataList[index];
    var that = this;
    HTTP({
      url: URL.order.cancelOrder,
      userToken: getUserToken(),
      data: {
        OrderInfoCode: ordermodel.OrderInfoCode,
        MemberId: getUserInfo().memberId,
      },
      success: (ress) => {
        wx.showToast({
          title: _('取消成功'),
          icon: 'succes',
          duration: 1000,
          mask: true
        })
        that.fetchDataList();//刷新订单列表
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  }
})